package cc.zstart.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class StringUtil {
	public static boolean strInArr(String a, String[] arr){
		if(arr == null) {
			return a == null;
		} else {
			for(String o : arr){
				if(StringUtils.equals(a, o)){
					return true;
				}
			}
		}
		return false;
	}
	
	public static boolean strInList(String a, List<String> list){
		if(list == null) {
			return a == null;
		} else {
			for(String o : list){
				if(StringUtils.equals(a, o)){
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * @Author DaiJG
	 * @Date 2018/1/18 15:23
	 * @Description 将一个字符串根据长度拆分成多个字串，中文字符长度为1，非中文字符长度为0.5
	 * @param str
	 * @param len
	 * @return
	 */
	public static List<String> splitByChinese(String str, int len){
		if (str == null) {
			return null;
		}
		if (str.length() <= len) {
			return ListUtil.listStr(str);
		}
		List<String> list = new ArrayList<>();
		String line = "";
		float lineLen = 0f;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			float currentLen = c > 255 ? 1 : 0.5f;
			if (lineLen + currentLen > len) {
				list.add(line);
				line = "";
				lineLen = 0;
			}
			lineLen += currentLen;
			line += c;
		}
		if (StringUtils.isNotBlank(line)) {
			list.add(line);
		}
		return list;
	}

	/**
	 * @Author DaiJG
	 * @Date 2018/1/18 15:52
	 * @Description 将一个字符串根据长度拆分成多个字串
	 * @param str
	 * @param len
	 * @return
	 */
	public static List<String> splitByLen(String str, int len){
		if (str == null) {
			return null;
		}
		List<String> list = new ArrayList<String>();
		for(int idx = 0;idx < str.length();){
			int end = Math.min(idx + len, str.length());
			list.add(str.substring(idx, end));
			idx = end;
		}
		return list;
	}

}
